package com.dkt.blogboot.util.blogUserEs;

import com.alibaba.fastjson.JSONObject;
import com.dkt.blogboot.entity.User;
import com.dkt.blogboot.resp.TagQueryResp;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component("esOperation")
public class ESOperation {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    public List<User> QueryFromES(String indexName, QueryBuilder queryBuilder, int from, int size) throws IOException {
        List<User> resultList = new ArrayList<>();

        SearchRequest request = new SearchRequest(indexName);
        request.source().query(queryBuilder).from(from).size(size);
        SearchResponse resp = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits searchHits = resp.getHits();
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String jsonResult = hit.getSourceAsString();
            System.out.println("在ES中查询到文档信息："+jsonResult);
            JSONObject jsonObject = JSONObject.parseObject(jsonResult);
            User user = new User();
            user.setId(jsonObject.getInteger("id"));
            user.setUsername(jsonObject.getString("username"));
            user.setPassword(jsonObject.getString("password"));
            user.setNickname(jsonObject.getString("nickname"));
            user.setStatus(jsonObject.getInteger("status"));
            resultList.add(user);
        }
        return resultList;
    }
}

